package com.yunwaikeji.gy_tool_library.utils.http.download;

import android.app.PendingIntent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.yunwaikeji.gy_tool_library.base.GYBaseUtils;
import com.yunwaikeji.gy_tool_library.utils.file.GYFileLoadListener;
import com.yunwaikeji.gy_tool_library.utils.file.GYFileUtils;
import com.yunwaikeji.gy_tool_library.utils.file.GYFileWriteTask;
import com.yunwaikeji.gy_tool_library.utils.http.GYHttpAsyncTask;
import com.yunwaikeji.gy_tool_library.utils.http.GYHttpListener;
import com.yunwaikeji.gy_tool_library.utils.notification.GYNotificationUtils;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;

public class GYDownloadTask extends GYHttpAsyncTask<GYDownloadTask, GYDownloadModel<?>> {
    private GYFileLoadListener fileLoadListener;
    private GYFileWriteTask fileWriteTask;
    private GYHttpAsyncTask<?, ?> httpAsyncTask;
    private File downloadFile;

    private final Handler handler = new Handler(Looper.getMainLooper());
    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            long now = fileWriteTask.getNowBytes();
            long total = fileWriteTask.getTotalBytes();
            long secondBytes = fileWriteTask.getSecondBytes();
            String nowS = GYFileUtils.getFormatSize((double) now);
            String totalS = GYFileUtils.getFormatSize((double) total);
            String secondBytesS = GYFileUtils.getFormatSize((double) secondBytes);
            int progress = 0;
            if (total > 0) {
                progress = (int) (now * 100 / total);
            }
            if (getHttpModel().isShowNoticeOnLoading()) {
                noticeOnLoading(progress, nowS, totalS, secondBytesS);
            }
            if (now >= total) {
                if (getHttpModel().isShowNoticeOnSuccess()) {
                    noticeOnSuccess();
                } else {
                    noticeOnLoading(progress, nowS, totalS, secondBytesS);
                }
                handler.removeCallbacks(this);
            } else {
                handler.postDelayed(this, 1000);
            }
        }
    };

    public GYDownloadTask setFileLoadListener(GYFileLoadListener fileLoadListener) {
        this.fileLoadListener = fileLoadListener;
        return this;
    }

    public Integer start(boolean reStart) {
        getHttpModel().setReStart(reStart);
        if (httpAsyncTask != null) {
            if (reStart) {
                if (httpAsyncTask.isStarting()) {
                    httpAsyncTask.setCanceled(true);
                }
            } else {
                onError("正在下载中...");
                return httpAsyncTask.getTagId();
            }
        }
        if (reStart && fileWriteTask != null && fileWriteTask.isStarting()) {
            GYNotificationUtils.getNotificationManager().cancel(httpAsyncTask.getTagId());
            fileWriteTask.setCanceled(true);
        }
//        if (getHttpModel().getCacheDirectory() == null) {
//            onError("请设置缓存路径");
//            return null;
//        }
        if (getHttpModel().getDownloadDirectory() == null) {
            onError("请设置下载路径");
            return null;
        }
        if (TextUtils.isEmpty(getHttpModel().getUrl())) {
            onError("url为空");
            return null;
        }
        if (TextUtils.isEmpty(getHttpModel().getName())) {
            String[] urls = getHttpModel().getUrl().split("/");
            String lastName = "";
            int i = urls.length;
            while (TextUtils.isEmpty(lastName)) {
                i--;
                lastName = urls[i];
                if (i == 0) {
                    break;
                }
            }
            getHttpModel().setName(lastName);
        }
        downloadFile = new File(getHttpModel().getDownloadDirectory(), getHttpModel().getName());
        return startHttp();
    }

    public Integer start() {
        return start(false);
    }

    public Integer reStart() {
        return start(true);
    }

    @Override
    public void onError(String error) {
        Log.e(getClass().getSimpleName(), error);
        if (fileLoadListener != null) {
            fileLoadListener.error(error);
            fileLoadListener.finish();
//            if (httpAsyncTask != null && !httpAsyncTask.isStarting()) {
//                fileLoadListener.finish();
//            }
        }
    }

    private Integer startHttp() {
        httpAsyncTask = new GYHttpAsyncTask<>()
                .setHttpModel(getHttpModel())
                .setResponseMainThread(false)
                .setHttpListener(new GYHttpListener<HttpURLConnection>() {
                    @Override
                    public void start() {
                        if (getHttpModel().isShowNoticeOnStart()) {
                            GYNotificationUtils.newNotificationManager()
                                    .setNotificationBuilder(
                                            GYNotificationUtils.getNotificationBuilder()
                                                    .setContentTitle("下载请求中"))
                                    .showOfId(httpAsyncTask.getTagId());
                        }
                        if (fileLoadListener != null) {
                            fileLoadListener.start();
                        }
                    }

                    @Override
                    public void stop() {
                        if (fileLoadListener != null) {
                            fileLoadListener.stop();
                        }
                    }

                    @Override
                    public void success(HttpURLConnection httpURLConnection) {
                        fileWriteTask = GYFileUtils.newFileWriteTask();
                        if (getHttpModel().isShowNoticeOnLoading()) {
                            handler.post(runnable);
                        }
                        try {
                            fileWriteTask.setReStart(getHttpModel().isReStart())
                                    .setCacheSize(getHttpModel().getCacheSize())
                                    .setInputStream(httpURLConnection.getInputStream())
                                    .setTotalBytes(httpURLConnection.getContentLength())
                                    .setWriteFile(downloadFile)
                                    .setRequestMainThread(true)
                                    .setFileLoadListener(new GYFileLoadListener() {
                                        @Override
                                        public void paused() {

                                        }

                                        @Override
                                        public void loading(long nowBytes, long totalBytes, long secondBytes) {
                                            if (fileLoadListener != null) {
                                                fileLoadListener.loading(nowBytes, totalBytes, secondBytes);
                                            }
                                        }

                                        @Override
                                        public void start() {

                                        }

                                        @Override
                                        public void stop() {

                                        }

                                        @Override
                                        public void success(String s) {
                                            if (getHttpModel().isShowNoticeOnSuccess()) {
                                                noticeOnSuccess();
                                            }
                                            if (fileLoadListener != null) {
                                                fileLoadListener.success(s);
                                            }
                                        }

                                        @Override
                                        public void error(String error) {
                                            onError(error);
                                        }

                                        @Override
                                        public void finish() {
                                            if (fileLoadListener != null) {
                                                fileLoadListener.finish();
                                            }
                                            httpURLConnection.disconnect();
                                        }
                                    });
                            fileWriteTask.start();
                        } catch (IOException e) {
                            e.printStackTrace();
                            onError(e.toString());
                        }
                    }

                    @Override
                    public void error(String error) {
                        onError(error);
                    }

                    @Override
                    public void finish() {
                    }
                });
        httpAsyncTask.start();
        return httpAsyncTask.getTagId();
    }

    private void noticeOnLoading(int progress, String nowS, String totalS, String secondBytesS) {
        GYNotificationUtils.newNotificationManager()
                .setNotificationBuilder(
                        GYNotificationUtils.getNotificationBuilder()
                                .setContentTitle("正在下载")
                                .setContentText(nowS + "/" + totalS + "--" + secondBytesS + "/s")
                                .setProgress(100, progress, false))
                .showOfId(httpAsyncTask.getTagId());
    }

    private void noticeOnSuccess() {
        File file1 = new File(getHttpModel().getDownloadDirectory(), getHttpModel().getName());
        PendingIntent pendingIntent = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(
                    GYNotificationUtils.getNotificationInitBuilder().getContext(),
                    PendingIntent.FLAG_MUTABLE,
                    GYFileUtils.getFileIntent(GYNotificationUtils.getNotificationInitBuilder().getContext(),
                            GYBaseUtils.getAuthority(),
                            file1),
                    PendingIntent.FLAG_MUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(
                    GYNotificationUtils.getNotificationInitBuilder().getContext(),
                    0,
                    GYFileUtils.getFileIntent(GYNotificationUtils.getNotificationInitBuilder().getContext(),
                            GYBaseUtils.getAuthority(),
                            file1),
                    0);
        }
        GYNotificationUtils.newNotificationManager()
                .setNotificationBuilder(
                        GYNotificationUtils.getNotificationBuilder()
                                .setContentIntent(pendingIntent)
                                .setProgress(100, 100, false)
                                .setAutoCancel(true)
                                .setContentTitle("下载完成")
                                .setContentText("点击打开"))
                .showOfId(httpAsyncTask.getTagId());
    }
}
